<template>
	<view class="conbox">
		<image class="share-icon" src="@/static/img/share-icon.png" @click="getShare"></image>
		<view class="container">
			<view class="main" id="postzpHtml">
				<view class="canvas-container">
					<view class="canvas-content" id="zhuanpano" style="">
						<view class="canvas-line">
							<view class="canvas-litem" v-for="(item,index) in awardsList" :key="index" :style="[{transform:'rotate('+item.lineTurn+')'}]"></view>
						</view>
						<view class="canvas-list">
							<view class="canvas-item" :style="[{zIndex:index}]" v-for="(item,index) in awardsList" :key="index">
								<view class="canvas-item-text" :style="[{transform:'rotate('+item.turn+')'}]">
									<text class="award-txt">{{item.award}}</text>
									<image :class="['award-img', !item.id && 'is-null']" :src="item.awardImg"></image>
								</view>
							</view>
						</view>
					</view>
					<view @tap="playReward" 
					class="canvas-btn"></view>
				</view>
				<view class="zpcj-num flex-center">
					<text class="num-txt">您还有机会再抽{{awardsConfig.emptionRestrict || '0'}}次</text>
				</view>
			</view>
			<view class="model-item">
				<view class="model-header flex-normal">
					<text class="header-txt">活动规则</text>
				</view>
				<view class="model-content">
					<view v-for="desc in awardsConfig.remarks" :key="desc" class="txt-item">
						{{desc}}
					</view>
				</view>
			</view>
			<view class="model-item">
				<view class="model-header flex-normal">
					<text class="header-txt">活动商家</text>
				</view>
				<view class="model-content flex-between shop-content">
					<image class="shop-cover" :src="getShopCover(shopInfo.imgUrlVos)"></image>
					<view class="shop-info flex-column">
						<text class="title-txt ellipsis-1">{{shopInfo.shopName}}</text>
						<text class="txt-item ellipsis-1" @click="openMap">{{shopInfo.shopAddress}}</text>
						<view class="info-icon-content flex-between">
							<u-icon name="phone" size="32rpx" color="#1A1A1A" @click="callPhone"></u-icon>
							<view class="flex-normal flex-center" v-if="location.distace">
								<text class="txt-item" style="padding-top: 10rpx; padding-right: 10rpx;">{{location.distace}} Km</text>
								<u-icon name="map" size="32rpx" color="#1A1A1A"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="model-item" v-if="logList.length">
				<view class="model-header flex-normal">
					<text class="header-txt">中奖记录</text>
				</view>
				<view class="model-content">
					<view v-for="desc in logList" :key="desc" class="txt-item">
						{{desc}}
					</view>
				</view>
			</view>
		</view>
		<view class="modal-container flex-center" v-if="boo.showModal">
			<view class="modal-content">
				<view class="modal-close" @click="boo.showModal = false">
					<u-icon name="close-circle-fill" size="60rpx" color="#fff"></u-icon>					
				</view>
				<image v-if="!activeAwards.id" class="modal-icon" src="@/static/img/no-award.png" mode="aspectFill"></image>
				<image v-else class="modal-icon" src="@/static/img/xiche.png" mode="aspectFill"></image>
				<view class="modal-txt">
					{{cumputedTxt()}}
				</view>
			</view>
		</view>
		<view class="hidden-user-share">
			<view class="user-share-container" id="postuserHtml">
				<view class="share-title">
					{{vuex_activity.activityName}}
				</view>
				<view class="share-content flex-between">
					<view class="left-content flex-column">
						<view class="user-info flex-normal">
							<image class="user-head" :src="baseUserData.headPortrait" mode="scaleToFill"></image>
							<text class="user-name">{{baseUserData.userNickName}}</text>
						</view>
						<view class="info-desc">
							长按识别二维码可立即抢购
						</view>
					</view>
					<rh-qrcode size="150" :qrcode="invitUrl || '--'"></rh-qrcode>
				</view>
			</view>
		</view>  
	</view>
</template>

<script>
	import html2canvas from "html2canvas";
	import {mapGetters} from 'vuex'
	import { getShopInfo } from '@/api/hd/index.js'
	import wechat from '@/script/wechat.js'
	import wxSDK from 'jweixin-module'
	import { lotteryDetails, lottery, lotteryLog } from '@/api/hd/index.js'
	export default {
		props: {
			baseUserData: {
				type: Object,
				default: () => {}
			},			
			invitUrl: {
				type: String,
				default: () => ''
			},
		},
		computed:{
			...mapGetters(['vuex_activity', 'vuex_needRegister'])
		},
		data() {
			return {
				boo: {
					isRuning: false, //正在转动
					showModal: false,
				},
				awardsConfig: {
					islimitation: true, // 是否有抽奖限制
					emptionRestrict: 0, // 剩余抽奖次数
					remarks: [],
					distace: ''
				},
				awardsList: [], // 奖项列表
				logList: [], // 中奖记录列表
				shopInfo: {}, 
				location: {},
				activeAwards: {}, //用户抽奖结果
				shareWidth: 0,
			}
		},
		async mounted() {
			uni.getSystemInfo({
				success: (res) => {
					let { windowWidth } = res
					this.shareWidth = windowWidth
				}
			})
			await this.showWxApp().then(async res => {
				// 获取奖品列表
				this.initdata()
				this.getLotteryLog()
				this.getShopInfo()
			})
		},
		methods: {
			callPhone(){
				uni.makePhoneCall({
					phoneNumber: this.shopInfo['csTel']
				})
			},
			openMap(){
				let _self = this
				const {latitudeAndLongitude, shopAddress, shopName} = this.shopInfo
				let arr = latitudeAndLongitude.split(',') || []
				let params = {
					name: shopName,
					address: shopAddress,
					latitude: parseFloat(arr[0] || '0'),
					longitude: parseFloat(arr[1] || '0')
				}
				if (wechat?.isWechat()) {
					wechat.callOpenLocation(params)
				}
			},
			getLocation(marker){
				let _self = this
				if (wechat?.isWechat()) {
					wechat.callLocation((location) => {
						_self.location = location
					}, (err) => {}, marker)
				}
			},
			getShopInfo(){
				let _self = this, { id } = this.vuex_activity
				if(!id) return
				getShopInfo(id).then(res => {
					let {latitudeAndLongitude} = res.data
					let arr = (latitudeAndLongitude || '').split(',')
					_self.shopInfo = res.data
					_self.getLocation({latitude: arr[0], longitude: arr[1]})
				})
			},
			getShopCover(list){
				if(!list || !list.length) return ''
				return list[0]['url']
			},
			cumputedTxt(){
				let _self = this, {id, serveName, itemNum} = this.activeAwards, {emptionRestrict} = this.awardsConfig
				if(id){
					return `恭喜您，获得${serveName}*${itemNum}，已发放至：我的卡券`
				}else{
					if(emptionRestrict <= 0) return `很遗憾您没中奖，下次再来吧`
					return `很遗憾您没中奖，还有${emptionRestrict}次机会，再接再厉`
				}
			},
			getLotteryLog(){
				let _self = this, { id, remarks, remark } = this.vuex_activity
				let arr = (remarks || remark || '').split(/[(\r\n)\r\n]+/) || [], list = []
					arr.forEach((i, idx) => {
						if(i.trim() != ''){
							list.push(i)
						}
					})
				_self.awardsConfig.remarks = list
				lotteryLog(id).then(res => {
					_self.logList = res.data || []
				})
			},
			// 初始化抽奖数据
			initdata(){
				let _self = this, { id } = this.vuex_activity
				lotteryDetails(id).then(res => {
					const { acddServes, number } = res.data
					let turnNum = 1 / acddServes.length * 360; // 文字旋转 turn 值
					_self.awardsList = acddServes.map((item, idx) => {
						let award = {
							turn: idx * turnNum + 'deg', //每个奖品块旋转的角度
							lineTurn: idx * turnNum + turnNum / 2 + 'deg', //奖品分割线的旋转角度
							id: item.id,
						}
						if(item.id){
							award.award = `${item.serveName}*${item.itemNum || ''}`
							award.awardImg = `../../static/img/xiche.png`
						}else{
							award.award = `${item.serveName}`
							award.awardImg = `../../static/img/xiaolian.png`	
						}
						return award
					})
					_self.awardsConfig.emptionRestrict = number
				})
			},
			//发起抽奖  
			playReward() {
				let _self = this, {emptionRestrict} = this.awardsConfig, { id } = this.vuex_activity
				
				if(this.vuex_needRegister){
					let {name} = _self.$$router.getRoute(_self)
					_self.$$router.replace({name: 'registerTel', query:{
						redirect: name
					}})
				}else{
					if(_self.boo.isRuning) return
					if (emptionRestrict <= 0) return uni.showToast({
						title: '抽奖次数已经用完',
						icon: 'none'
					})
					let params = {
						"address": _self.location['address'], //购买数量
						sharerUserId: _self.$route.query['i'] || ''
					}
					_self.boo.isRuning = true;
					lottery(id, params).then(res => {
						_self.animation(res.data)
						_self.activeAwards = res.data
					}).catch(() => {
						_self.boo.isRuning = false;
					})
				}
				
			},
			
			animation(res){
				let _self = this, { id } = res
				let awardIndex = _self.awardsList.findIndex(i => i.id == id)
				//中奖index
				let awardsNum = _self.awardsList;
				let runNum = 4; //旋转8周  
				let duration = 4000; //时长
				
				// 旋转角度  
				_self.runDeg = _self.runDeg || 0;
				let preDeg = _self.runDeg
				_self.runDeg = _self.runDeg + (360 - _self.runDeg % 360) + (360 * runNum - awardIndex * (360 / awardsNum.length)) +1
				//创建动画
				document.getElementById('zhuanpano').style='animation:rotate_before 4s 0ms ease forwards;'
				if(document.styleSheets[0].cssRules.length>0){
					Array.from(document.styleSheets[0].cssRules).forEach(function(element,index){
						if(element.name == 'rotate_before'){
							// 删除上次插入的动画
							document.styleSheets[0].deleteRule(index)
						}
					})
				}					
				// 插入定义的动画
				document.styleSheets[0].insertRule("@keyframes rotate_before{from{ transform: rotate("+preDeg+"deg); }to{ transform: rotate("+_self.runDeg+"deg);}}",8);
				
				// 中奖提示  
				let awardsConfig = _self.awardsConfig;
				_self.awardsConfig.emptionRestrict --
				setTimeout(function() {
					document.getElementById('zhuanpano').style=''
					_self.boo.isRuning = false;
					_self.boo.showModal = true
				}.bind(_self), duration);
			},
			makeCanvas(params){
			  let _self = this
			  return new Promise((resolve, reject) => {
			    html2canvas(params.domObj, {
			      allowTaint: true,
			      useCORS: true,
						scale: 2,
						dpi: 600,
			      width: params.clientWidth,
			      height: params.clientHeight,
			      scrollY: -18,
			      scrollX: -0,
			      onclone(doc) {}
			    }).then(canvas => {
			      /** 新Image对象，可以理解为DOM */
			      let image = new Image();
			      /** 解决跨域 Canvas 污染问题 */
			      image.setAttribute("crossOrigin", "anonymous");
			      let imgUrl = canvas.toDataURL("image/jpge");
			      // this.imgUrl1 = imgUrl1
			      resolve(imgUrl)
			    });
			  })
			},
			/** 将html元素转换成海报图片 */
			async getShare() {
				let _self = this
				if(this.vuex_needRegister){
					let {name} = _self.$$router.getRoute(_self)
					_self.$$router.replace({name: 'registerTel', query:{
						redirect: name
					}})
				}else{
					uni.showLoading({title: '加载中',mask: true});
					const posterHtml1 = document.querySelector('#postzpHtml');
					const posterHtml2 = document.querySelector('#postuserHtml');
					const img1 = await this.makeCanvas({
						domObj: posterHtml1, 
						clientHeight: posterHtml1.clientHeight, 
						clientWidth: posterHtml1.clientWidth, 
						name: '1'
					})
					
					const img2 = await this.makeCanvas({
						domObj: posterHtml2, 
						clientHeight: posterHtml2.clientHeight, 
						clientWidth: posterHtml2.clientWidth, 
						name: '2'
					})
					const img = await this.composeImgs(
						{ url: img1, 
							width: posterHtml1.clientWidth,
							height: posterHtml1.clientHeight,
						}, {
							url: img2, 
							width: posterHtml2.clientWidth,
							height: posterHtml2.clientHeight,
						})
					uni.hideLoading();
					this.$emit('active-share', img)
				}
			},
			appDrawImage(canvas, context, img, positionArr){
				let _self = this
				return new Promise((resolve, reject) => {
					const myImage = new Image();
					myImage.src = img.url;
					myImage.crossOrigin = 'Anonymous';
					myImage.onload = () => {
					  context.drawImage(myImage, 0, positionArr[0], _self.shareWidth, img.height); // 设置坐标并绘制
						const base64 = canvas.toDataURL('image/png'); //获取base64的图片流
						resolve(base64); // 成功之后返回图片路径
					};
				})
			},
			// 合成图片
			composeImgs(img1, img2) {
			  return new Promise(async (resolve, reject) => {
			    // 1，先创建一个画布
			    let canvas = document.createElement('canvas');
			    //2，创建画笔
			    const context = canvas.getContext('2d');
			    //3，设置背景的宽高
			    canvas.width = img1.width;
			    canvas.height = img1.height + img2.height;
					await this.appDrawImage(canvas, context, img1, [0])
					const base64 = await this.appDrawImage(canvas, context, img2, [img1.height])
					resolve(base64)
			  });
			},
		}

	}
</script>
<style scoped lang="scss">
	@mixin fontStyle($color, $size, $weight: 500) {
		color: $color;
		font-size: $size;
		font-weight: $weight;
	}
	.share-icon{
		position: fixed;
		width: 110rpx;
		height: 110rpx;
		z-index: 300;
		right: 30rpx;
		top: 45%;
	}
	.conbox {
		width: 750upx;
		min-height: 100vh;
		overflow-x: hidden;
		overflow-y: scroll;
		background-color: #ed304e;
		.container{		
			padding-bottom: 80rpx;
		}
		.main{	
			background: url('@/static/img/bg.png') no-repeat top;
			background-size: cover;
			padding-top: 360rpx;
			margin-bottom: 100rpx;
			position: relative;
			.zpcj-num{
				position: absolute;
				left: 0;
				right: 0;
				height: 91rpx;
				background: url('@/static/img/num.png') center no-repeat;
				background-size: contain;
				.num-txt{
					font-size: 24rpx;
					color: #ED304E;
					font-weight: 500;
					transform: translateY(-18rpx);
				}
			}
		}
		.model-item{
			position: relative;
			margin: 30rpx 30rpx 0;
			padding-top: 110rpx;
			.model-header{
				top: 0;
				left: 0;
				right: 0;
				position: absolute;
				background: url('@/static/img/model-header-bg.png') no-repeat center;
				background-size: cover;
				height: 160rpx;
				z-index: 0;
				.header-txt{
					color: #fff;
					font-size: 32rpx;
					font-weight: 500;
					transform: translate(160rpx, -15rpx);
				}
			}
			.model-content{
				border: 18rpx solid #FFAE5E;
				border-radius: 30rpx;
				padding: 24rpx 20rpx;
				position: relative;
				z-index: 1;
				background-color: #FFEBD7;
			}
			.txt-item{
				font-size: 24rpx;
				font-weight: 400;
				color: #111111;
				margin-bottom: 10rpx;
			}
			.shop-content{
				align-items: flex-start;
				.shop-cover{
					height: 154rpx;
					width: 154rpx;
					margin-right: 26rpx;
				}
				.shop-info{
					width: 70%;
					.title-txt{
						font-size: 32rpx;
						color: #111111;
						font-weight: 500;
						margin-bottom: 40rpx;
					}
				}
			}
		}
	}
	.modal-container{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		background: url('@/static/img/mask-bg.png') no-repeat center;
		z-index: 500;
		background-size: cover;
		.modal-content{
			width: 575rpx;
			height: 356rpx;
			border-radius: 20rpx;
			background-color: #FEF7DD;
			padding: 40rpx 60rpx;
			position: relative;
			.modal-icon{
				display: block;
				width: 431rpx;
				height: 218rpx;
			}
			.modal-txt{
				margin-top: 20rpx;
				font-size: 20rpx;
				color: #803516;
				font-weight: 500;
				text-align: center;
			}
			.modal-close{
				position: absolute;
				bottom: -120rpx;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
	.hidden-user-share{
		height: 0;
		overflow: hidden;
		.user-share-container{
			padding: 30rpx 20rpx;
			background-color: #fff;
			.share-title{
				text-align: center;
				@include fontStyle(#3D3D3D, 32rpx);
			}
			.share-content{
				padding: 30rpx 100rpx 0;
				.left-content{
					.user-info{
						.user-head{
							height: 60rpx;
							width: 60rpx;
							border-radius: 6rpx;
						}
						.user-name{
							margin-left: 10rpx;
							@include fontStyle(#3D3D3D, 24rpx);
						}
					}
					.info-desc{
						margin-top: 10rpx;
						@include fontStyle(#3D3D3D, 24rpx);
					}
				}
			}
		}
	}
	image.cont {
		width: 750upx;
		min-height: 100vh;
		height: auto;
		position: relative;
	}
	// image.cont {
	// 	height: 100%;
	// 	position: absolute;
	// 	z-index: 0;
	// }

	/* 转盘 */
	.canvas-container {
		margin: 30rpx auto 0;
		position: relative;
		width: 600upx;
		height: 600upx;
		background: url(../../static/img/circle.png) no-repeat;
		background-size: cover;
		border-radius: 50%;
		.canvas-content {
			position: absolute;
			left: 0;
			top: 0;
			z-index: 1;
			display: block;
			width: 600upx;
			height: 600upx;
			border-radius: inherit;
			/* background-clip: padding-box; */
			/* background-color: #ffcb3f; */
		}
		.canvas-line {
			position: absolute;
			left: 0;
			top: 0;
			width: inherit;
			height: inherit;
			z-index: 99;
			.canvas-litem {
				position: absolute;
				left: 300upx;
				top: 0;
				width: 3upx;
				height: 300upx;
				background-color: rgba(228, 55, 14, 0.4);
				overflow: hidden;
				-webkit-transform-origin: 50% 300upx;
				transform-origin: 50% 300upx;
			}
		}
		.canvas-list {
			position: absolute;
			left: 0;
			top: 0;
			width: inherit;
			height: inherit;
			z-index: 9999;
			.canvas-item {
				position: absolute;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				color: #e4370e;
				/* text-shadow: 0 1upx 1upx rgba(255, 255, 255, 0.6); */
			}
			.canvas-item-text {
				position: relative;
				display: block;
				padding-top: 46upx;
				margin: 0 auto;
				text-align: center;
				-webkit-transform-origin: 50% 300upx;
				transform-origin: 50% 300upx;
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #FB778B;
				width: 180rpx;
				.award-txt{
					font-size: 24rpx;
				}
				.award-img{
					width: 110rpx;
					height: 54rpx;
					margin-top: 30rpx;
					&.is-null{
						width: 54rpx;
					}
				}
			}
		}
	}
	.canvas-btn {
		position: absolute;
		left: 50%;
		top: 50%;
		z-index: 400;
		width: 214rpx;
		height: 214rpx;
		background: url('@/static/img/btn-bg.png') center no-repeat;
		background-size: contain;
		transform: translate(-50%,-50%);
	}

</style>
